<template>
  <AdVxeModal
    v-bind="$attrs"
    :id="id"
    :title="title"
    :width="width"
    :height="height"
    @register="register"
    @ok="handleOk"
  >
    <AdVxeTable @register="registerTable" @cell-dbclick="cellDblclickEvent" />
  </AdVxeModal>
</template>
<script lang="ts" setup>
  import { watch, computed, ref } from 'vue';
  import { AdVxeModal, useModalInner } from '@/components/AdVxeModal';
  import { AdVxeTable, useAdVxeTable, VxeGridDefines } from '@/components/AdVxeTable';

  import { isFunction } from '@/utils/is';

  import { castToVxeSize } from './types';
  import { dialogProps } from './props';

  defineOptions({ name: 'AdChooseListDialog' });
  const props = defineProps(dialogProps);

  const selectFnRef = ref<(data: Recordable[]) => Promise<boolean | undefined | void>>();
  // 模态窗体内部注册
  const [register, { closeModal, changeOkLoading }] = useModalInner((data) => {
    if (data.selectFn && isFunction(data.selectFn)) {
      selectFnRef.value = data.selectFn;
    }
  });

  // 表格注册
  const [registerTable, { getTable, setData: setTableData }] = useAdVxeTable({
    id: props.id ?? 'ad-choose-list-dialog-table',
    // 表标题呈现器
    title: undefined,
    // 表格数据接口请求对象
    api: props.api,
    searchInfo: props.searchInfo,
    // 表单列信息 BasicColumn[]
    columns: props.columns,
    // dataSource: props.data,
    size: castToVxeSize(props.tableSize), // 表格大小
    // 使用搜索表单
    searchForm: true,
    // 是否显示表格边框
    border: true,
    // toolbarConfig: { enabled: false },
    toolbarConfig: {
      print: false,
      refresh: false,
      zoom: false,
    },
    clickToSelect: true, // 点击行是否选中 checkbox 或者 radio。
    selection: props.multiple ? 'checkbox' : 'radio',
  });

  watch(
    () => props.data,
    (values) => {
      setTableData(values);
    },
  );

  /** 获取选择函数 */
  const getSelectFn = computed(() => {
    const { selectFn } = props;
    const selectFunc = selectFnRef.value;
    if (selectFunc && isFunction(selectFunc)) {
      return selectFunc;
    } else {
      return selectFn;
    }
  });

  /** 单元格被双击时会触发该事件 */
  async function cellDblclickEvent(e: VxeGridDefines.CellDblclickEventParams) {
    if (!props.multiple) {
      changeOkLoading(true);
      try {
        const rows = [e.row];
        const flag = await emitSelect(rows);
        if (flag === false) {
          // closeModal();
        } else {
          closeModal();
        }
      } finally {
        changeOkLoading(false);
      }
    }
  }

  /** 处理确定按钮 */
  async function handleOk() {
    changeOkLoading(true);
    try {
      let rows: Recordable[] = [];
      const table = getTable();
      if (table) {
        if (!props.multiple) {
          const radioRecord = table.getRadioRecord();
          if (radioRecord) {
            rows = [...rows, radioRecord];
          }
        } else {
          const checkboxRecords = table.getCheckboxRecords();
          if (checkboxRecords?.length > 0) {
            rows = [...rows, ...checkboxRecords];
          }
        }
      }
      const flag = await emitSelect(rows);
      if (flag === false) {
        // closeModal();
      } else {
        closeModal();
      }
    } finally {
      changeOkLoading(false);
    }
  }

  /** 触发数据选择事件 */
  async function emitSelect(records: Recordable[]) {
    const selectFunc = getSelectFn.value;
    if (selectFunc && isFunction(selectFunc)) {
      const flag = await selectFunc(records);
      return flag;
    }
  }
</script>
